<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <title>躲避飞刀 - 减压游戏</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        touch-action: manipulation;
        user-select: none;
        -webkit-user-select: none;
      }

      body {
        font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
        background: linear-gradient(to bottom, #f0f0f0 0%, #dadada 100%);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100vh;
        width: 100vw;
        overflow: hidden;
        position: fixed;
      }

      #gameContainer {
        position: relative;
        width: 100%;
        max-width: 600px;
        height: 100%;
        max-height: 800px;
        overflow: hidden;
      }

      canvas {
        display: block;
        background-color: #f5f5f5;
        width: 100%;
        height: 100%;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        border-radius: 8px;
      }

      .ui-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 10;
      }

      .ui-content {
        background-color: white;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        max-width: 80%;
      }

      .ui-title {
        font-size: 24px;
        margin-bottom: 10px;
        color: #333;
      }

      .ui-score {
        font-size: 36px;
        font-weight: bold;
        color: #e74c3c;
        margin: 10px 0;
      }

      .ui-button {
        background-color: #e74c3c;
        color: white;
        border: none;
        padding: 12px 30px;
        border-radius: 50px;
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
        margin-top: 15px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        transition: all 0.2s;
      }

      .ui-button:hover,
      .ui-button:active {
        transform: scale(1.05);
        background-color: #c0392b;
      }

      .score-display {
        position: absolute;
        top: 20px;
        left: 20px;
        font-size: 24px;
        font-weight: bold;
        color: #e74c3c;
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
        z-index: 5;
      }

      .back-button {
        position: absolute;
        top: 20px;
        right: 20px;
        background-color: rgba(255, 255, 255, 0.7);
        border: none;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        font-size: 18px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        z-index: 5;
      }

      .instruction {
        font-size: 16px;
        color: #555;
        margin: 15px 0;
      }

      .control-area {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 35%;
        z-index: 5;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .joystick-area {
        width: 120px;
        height: 120px;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 60px;
        position: relative;
        display: none; /* 默认隐藏，在移动设备上显示 */
      }

      .joystick-knob {
        width: 50px;
        height: 50px;
        background-color: rgba(231, 76, 60, 0.8);
        border-radius: 25px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      @media (max-width: 768px) {
        .joystick-area {
          display: block;
        }
      }
    </style>
  </head>
  <body>
    <div id="gameContainer">
      <canvas id="gameCanvas"></canvas>
      <div id="scoreDisplay" class="score-display">分数: 0</div>
      <button id="backButton" class="back-button">←</button>

      <!-- 虚拟摇杆（移动设备） -->
      <div class="control-area">
        <div id="joystickArea" class="joystick-area">
          <div id="joystickKnob" class="joystick-knob"></div>
        </div>
      </div>

      <!-- 开始游戏UI -->
      <div id="startScreen" class="ui-overlay">
        <div class="ui-content">
          <h1 class="ui-title">躲避飞刀</h1>
          <p class="instruction">在屏幕上拖动方块躲避红色飞刀！</p>
          <p class="instruction">桌面：使用方向键移动</p>
          <p class="instruction">移动设备：使用虚拟摇杆控制</p>
          <button id="startButton" class="ui-button">开始游戏</button>
        </div>
      </div>

      <!-- 游戏结束UI -->
      <div id="gameOverScreen" class="ui-overlay" style="display: none">
        <div class="ui-content">
          <h1 class="ui-title">游戏结束</h1>
          <p>你的得分</p>
          <div id="finalScore" class="ui-score">0</div>
          <button id="restartButton" class="ui-button">再试一次</button>
        </div>
      </div>
    </div>

    <script>
      // 获取DOM元素
      const canvas = document.getElementById("gameCanvas");
      const ctx = canvas.getContext("2d");
      const scoreDisplay = document.getElementById("scoreDisplay");
      const finalScoreDisplay = document.getElementById("finalScore");
      const startScreen = document.getElementById("startScreen");
      const gameOverScreen = document.getElementById("gameOverScreen");
      const startButton = document.getElementById("startButton");
      const restartButton = document.getElementById("restartButton");
      const backButton = document.getElementById("backButton");
      const joystickArea = document.getElementById("joystickArea");
      const joystickKnob = document.getElementById("joystickKnob");

      // 设置游戏参数
      let gameWidth, gameHeight;
      let gameRunning = false;
      let animationId;

      // 调整Canvas大小为容器大小
      function resizeCanvas() {
        const container = document.getElementById("gameContainer");
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
        gameWidth = canvas.width;
        gameHeight = canvas.height;

        // 如果游戏正在运行，重新定位玩家位置
        if (gameRunning && player) {
          // 保持玩家在相对位置
          player.x = Math.min(Math.max(player.x, 0), gameWidth - player.size);
          player.y = Math.min(Math.max(player.y, 0), gameHeight - player.size);
        }
      }

      // 监听窗口大小变化
      window.addEventListener("resize", resizeCanvas);

      // 初始化Canvas尺寸
      resizeCanvas();

      // 检测是否为移动设备
      const isMobile =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        );

      // 游戏对象
      let player, knives, score;

      // 初始化游戏
      function initGame() {
        const playerSize = Math.min(gameWidth, gameHeight) * 0.05;

        player = {
          x: gameWidth / 2 - playerSize / 2,
          y: gameHeight / 2 - playerSize / 2,
          size: playerSize,
          speed: gameWidth * 0.015,
          dx: 0,
          dy: 0,
          color: "#3498db",
        };

        knives = [];
        score = 0;
        scoreDisplay.textContent = "分数: " + score;

        // 重置游戏难度
        knifeSpeed = gameWidth * 0.005;
        knifeSpawnRate = 500; // 每500分数生成一把新飞刀

        // 创建初始飞刀
        createKnife();
      }

      // 绘制玩家
      function drawPlayer() {
        // 绘制边框
        ctx.strokeStyle = "#2980b9";
        ctx.lineWidth = player.size * 0.1;
        ctx.strokeRect(player.x, player.y, player.size, player.size);

        // 绘制主体
        ctx.fillStyle = player.color;
        ctx.fillRect(player.x, player.y, player.size, player.size);

        // 玩家内部图案
        const padding = player.size * 0.2;
        ctx.fillStyle = "#2980b9";
        ctx.fillRect(
          player.x + padding,
          player.y + padding,
          player.size - padding * 2,
          player.size - padding * 2
        );
      }

      // 创建飞刀
      function createKnife() {
        const knifeSize = Math.min(gameWidth, gameHeight) * 0.03;
        const edge = Math.floor(Math.random() * 4);
        let x, y, dx, dy;

        switch (edge) {
          case 0: // 从上边缘出现
            x = Math.random() * gameWidth;
            y = -knifeSize;
            dx = (Math.random() - 0.5) * knifeSpeed;
            dy = knifeSpeed;
            break;
          case 1: // 从下边缘出现
            x = Math.random() * gameWidth;
            y = gameHeight;
            dx = (Math.random() - 0.5) * knifeSpeed;
            dy = -knifeSpeed;
            break;
          case 2: // 从左边缘出现
            x = -knifeSize;
            y = Math.random() * gameHeight;
            dx = knifeSpeed;
            dy = (Math.random() - 0.5) * knifeSpeed;
            break;
          case 3: // 从右边缘出现
            x = gameWidth;
            y = Math.random() * gameHeight;
            dx = -knifeSpeed;
            dy = (Math.random() - 0.5) * knifeSpeed;
            break;
        }

        knives.push({
          x: x,
          y: y,
          size: knifeSize,
          dx: dx,
          dy: dy,
          rotation: Math.atan2(dy, dx),
          opacity: 0.8,
        });
      }

      // 绘制飞刀
      function drawKnives() {
        knives.forEach((knife) => {
          ctx.save();
          ctx.translate(knife.x + knife.size / 2, knife.y + knife.size / 2);
          ctx.rotate(knife.rotation);

          // 刀刃
          ctx.fillStyle = `rgba(231, 76, 60, ${knife.opacity})`;
          ctx.fillRect(
            -knife.size / 2,
            -knife.size / 2,
            knife.size * 1.5,
            knife.size
          );

          // 刀柄
          ctx.fillStyle = "#34495e";
          ctx.fillRect(
            -knife.size / 2,
            -knife.size / 4,
            knife.size * 0.5,
            knife.size / 2
          );

          ctx.restore();
        });
      }

      // 更新飞刀位置
      function updateKnives() {
        // 首先更新现有飞刀位置
        for (let i = knives.length - 1; i >= 0; i--) {
          const knife = knives[i];
          knife.x += knife.dx;
          knife.y += knife.dy;

          // 检查是否完全离开屏幕
          if (
            knife.x < -knife.size * 2 ||
            knife.x > gameWidth + knife.size * 2 ||
            knife.y < -knife.size * 2 ||
            knife.y > gameHeight + knife.size * 2
          ) {
            knives.splice(i, 1);
          }
        }

        // 根据得分生成新飞刀
        if (score % knifeSpawnRate === 0 && score > 0) {
          createKnife();
          // 随着得分增加，提高难度
          if (knives.length < 15) {
            // 限制最大飞刀数量
            knifeSpeed *= 1.05;
            knifeSpawnRate = Math.max(100, knifeSpawnRate - 50);
          }
        }
      }

      // 更新玩家位置
      function updatePlayer() {
        // 移动玩家
        player.x += player.dx;
        player.y += player.dy;

        // 确保玩家不会离开屏幕
        player.x = Math.max(0, Math.min(gameWidth - player.size, player.x));
        player.y = Math.max(0, Math.min(gameHeight - player.size, player.y));
      }

      // 检查碰撞
      function checkCollision() {
        for (let i = 0; i < knives.length; i++) {
          const knife = knives[i];
          if (
            player.x < knife.x + knife.size &&
            player.x + player.size > knife.x &&
            player.y < knife.y + knife.size &&
            player.y + player.size > knife.y
          ) {
            return true;
          }
        }
        return false;
      }

      // 绘制粒子效果
      function drawParticles() {
        // 如果有粒子数组并且有粒子，绘制它们
        if (particles && particles.length) {
          for (let i = 0; i < particles.length; i++) {
            const p = particles[i];
            ctx.fillStyle = `rgba(231, 76, 60, ${p.opacity})`;
            ctx.beginPath();
            ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
            ctx.fill();
          }
        }
      }

      // 更新粒子效果
      function updateParticles() {
        if (particles && particles.length) {
          for (let i = particles.length - 1; i >= 0; i--) {
            const p = particles[i];
            p.x += p.dx;
            p.y += p.dy;
            p.opacity -= 0.02;
            if (p.opacity <= 0) {
              particles.splice(i, 1);
            }
          }
        }
      }

      // 创建爆炸效果
      function createExplosion(x, y) {
        particles = [];
        for (let i = 0; i < 30; i++) {
          const angle = Math.random() * Math.PI * 2;
          const speed = Math.random() * 3 + 1;
          particles.push({
            x: x,
            y: y,
            dx: Math.cos(angle) * speed,
            dy: Math.sin(angle) * speed,
            size: Math.random() * 3 + 1,
            opacity: 1,
          });
        }
      }

      // 绘制背景
      function drawBackground() {
        // 绘制网格背景
        ctx.strokeStyle = "rgba(0,0,0,0.05)";
        ctx.lineWidth = 1;

        const gridSize = 30;
        for (let x = 0; x <= gameWidth; x += gridSize) {
          ctx.beginPath();
          ctx.moveTo(x, 0);
          ctx.lineTo(x, gameHeight);
          ctx.stroke();
        }

        for (let y = 0; y <= gameHeight; y += gridSize) {
          ctx.beginPath();
          ctx.moveTo(0, y);
          ctx.lineTo(gameWidth, y);
          ctx.stroke();
        }
      }

      let knifeSpeed, knifeSpawnRate, playerSize;
      let particles = [];
      let joystickActive = false;
      let joystickStartX, joystickStartY;

      // 游戏循环
      function gameLoop() {
        ctx.clearRect(0, 0, gameWidth, gameHeight);

        drawBackground();
        drawPlayer();
        drawKnives();
        drawParticles();

        updatePlayer();
        updateKnives();
        updateParticles();

        // 增加得分
        score++;
        scoreDisplay.textContent = "分数: " + Math.floor(score / 10);

        if (checkCollision()) {
          createExplosion(
            player.x + player.size / 2,
            player.y + player.size / 2
          );
          gameOver();
        } else {
          animationId = requestAnimationFrame(gameLoop);
        }
      }

      // 游戏结束
      function gameOver() {
        cancelAnimationFrame(animationId);
        gameRunning = false;
        finalScoreDisplay.textContent = Math.floor(score / 10);
        gameOverScreen.style.display = "flex";
      }

      // 开始游戏
      function startGame() {
        startScreen.style.display = "none";
        gameOverScreen.style.display = "none";
        initGame();
        gameRunning = true;
        gameLoop();
      }

      // 虚拟摇杆控制（移动设备）
      function setupJoystick() {
        // 初始化摇杆位置
        const joystickRect = joystickArea.getBoundingClientRect();
        joystickStartX = joystickRect.left + joystickRect.width / 2;
        joystickStartY = joystickRect.top + joystickRect.height / 2;

        // 触摸开始
        joystickArea.addEventListener(
          "touchstart",
          function (e) {
            e.preventDefault();
            joystickActive = true;
            updateJoystick(e.touches[0].clientX, e.touches[0].clientY);
          },
          { passive: false }
        );

        // 触摸移动
        document.addEventListener(
          "touchmove",
          function (e) {
            if (joystickActive) {
              e.preventDefault();
              updateJoystick(e.touches[0].clientX, e.touches[0].clientY);
            }
          },
          { passive: false }
        );

        // 触摸结束
        document.addEventListener("touchend", function () {
          joystickActive = false;
          resetJoystick();
          if (player) {
            player.dx = 0;
            player.dy = 0;
          }
        });

        document.addEventListener("touchcancel", function () {
          joystickActive = false;
          resetJoystick();
          if (player) {
            player.dx = 0;
            player.dy = 0;
          }
        });
      }

      // 更新摇杆位置和状态
      function updateJoystick(touchX, touchY) {
        if (!joystickActive || !player) return;

        const joystickRect = joystickArea.getBoundingClientRect();
        const centerX = joystickRect.left + joystickRect.width / 2;
        const centerY = joystickRect.top + joystickRect.height / 2;

        // 计算触摸点与摇杆中心的距离
        let dx = touchX - centerX;
        let dy = touchY - centerY;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 限制摇杆在区域内
        const maxDistance = joystickRect.width / 2;
        if (distance > maxDistance) {
          dx = (dx * maxDistance) / distance;
          dy = (dy * maxDistance) / distance;
        }

        // 设置摇杆位置
        joystickKnob.style.transform = `translate(${dx}px, ${dy}px)`;

        // 更新玩家移动
        const normDx = dx / maxDistance;
        const normDy = dy / maxDistance;
        player.dx = normDx * player.speed;
        player.dy = normDy * player.speed;
      }

      // 重置摇杆位置
      function resetJoystick() {
        joystickKnob.style.transform = "translate(0, 0)";
      }

      // 键盘控制
      function setupKeyboardControls() {
        const keys = {
          ArrowUp: false,
          ArrowDown: false,
          ArrowLeft: false,
          ArrowRight: false,
        };

        document.addEventListener("keydown", function (e) {
          if (keys.hasOwnProperty(e.key)) {
            keys[e.key] = true;
            updatePlayerMovement();
          }
        });

        document.addEventListener("keyup", function (e) {
          if (keys.hasOwnProperty(e.key)) {
            keys[e.key] = false;
            updatePlayerMovement();
          }
        });

        function updatePlayerMovement() {
          if (!player || !gameRunning) return;

          player.dx = 0;
          player.dy = 0;

          if (keys.ArrowLeft) player.dx = -player.speed;
          if (keys.ArrowRight) player.dx = player.speed;
          if (keys.ArrowUp) player.dy = -player.speed;
          if (keys.ArrowDown) player.dy = player.speed;
        }
      }

      // 初始化控制
      function initControls() {
        if (isMobile) {
          setupJoystick();
        }
        setupKeyboardControls();
      }

      // 点击开始按钮
      startButton.addEventListener("click", startGame);

      // 点击重新开始按钮
      restartButton.addEventListener("click", startGame);

      // 返回按钮点击事件
      backButton.addEventListener("click", function () {
        window.location.href = "index.html";
      });

      // 初始化控制
      initControls();
    </script>
  </body>
</html>
